import {
  AuthModel
} from '../../models/authData.js'
import { config } from '../../config.js'
let authModel = new AuthModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    priSeries: [],
    priSeriesIndex: 0,
    priYears: [],
    priYearsIndex: 0,
    secSeries: [],
    secSeriesIndex: 0,
    secYears: [],
    secYearsIndex: 0,
    gatheringCode: '',
    saveGatheringCode: '',
    quaCertificate: [],
    saveQuaCertificate: [],
    idCertificate: [],
    saveIdCertificate: [],
    awardCertificate: [],
    saveAwardCertificate: [],
    authenticationInfo: '',
    otherDes: '',
    btnClickStatus: '',
    saveData: {},
    FItEmpId: '',
  },

  pickGatheringCode(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          gatheringCode: res.tempFilePaths[0]
        })
      }
    })
  },

  deleteGatherCode(e) {
    this.setData({
      gatheringCode: ''
    })
  },

  pickQuaCertificate(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempArr = that.data.quaCertificate
        tempArr.push(res.tempFilePaths[0])
        that.setData({
          quaCertificate: tempArr
        })
      }
    })
  },

  deleteQuaCertificate(e) {
    var tempArr = this.data.quaCertificate
    tempArr.splice(e.currentTarget.id, 1)
    this.setData({
      quaCertificate: tempArr
    })
  },

  pickIdCertificate(e) {
    if (this.data.idCertificate.length == 2) {
      return
    }
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempArr = that.data.idCertificate
        tempArr.push(res.tempFilePaths[0])
        that.setData({
          idCertificate: tempArr
        })
      }
    })
  },

  deleteIdCertificate(e) {
    var tempArr = this.data.idCertificate
    tempArr.splice(e.currentTarget.id, 1)
    this.setData({
      idCertificate: tempArr
    })
  },

  pickAwardCertificate(e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempArr = that.data.awardCertificate
        tempArr.push(res.tempFilePaths[0])
        that.setData({
          awardCertificate: tempArr
        })
      }
    })
  },

  deleteAwardCertificate(e) {
    var tempArr = this.data.awardCertificate
    tempArr.splice(e.currentTarget.id, 1)
    this.setData({
      awardCertificate: tempArr
    })
  },

  checkRequired(e) {
    this.setData({
      btnClickStatus: e.currentTarget.id
    })
    if (this.data.idCertificate.length < 2) {
      wx.showModal({
        showCancel: false,
        title: '提示',
        content: '请上传身份证正反面'
      })
      return
    }
    wx.showLoading({
      mask: true
    })
    this.uploadGatheringCode()
  },

  uploadGatheringCode() {
    var that = this
    var uuid = /[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/;
    if (uuid.test(that.data.gatheringCode) || !that.data.gatheringCode) {
      this.setData({
        saveGatheringCode: this.data.gatheringCode
      })
      that.uploadQuaCertificate({
        path: that.data.quaCertificate
      })
      return
    }
    wx.uploadFile({ 
      url: `${config.api_base_url}api/Ecp.Picture.upload.jup`,
      filePath: this.data.gatheringCode,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        'Cookie': 'MEETREND_CRM_TOKEN=' + wx.getStorageSync('token')
      },
      formData: {
        'user': 'test'
      },
      success: function(res) {        
        that.setData({
          saveGatheringCode: JSON.parse(res.data).data.pictureId
        })
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
      },
      fail: function(e) {
        wx.showModal({
          title: '提示',
          content: '上传失败',
          showCancel: false
        })
      },
      complete: function() {
        that.uploadQuaCertificate({
          path: that.data.quaCertificate
        })
      }
    })
  },

  uploadQuaCertificate(data) {
    var that = this
    var i = data.i ? data.i : 0
    if (data.path.length === i) {
      that.uploadIdCertificate({
        path: that.data.idCertificate
      })
      return
    }
    var uuid = /[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/;
    if (uuid.test(data.path[i])) {
      var array = that.data.saveQuaCertificate
      array.push(data.path[i])
      that.setData({
        saveQuaCertificate: array
      })
      i++
      data.i = i
      that.uploadQuaCertificate(data)
    } else {
      wx.uploadFile({
        url: `${config.api_base_url}api/Ecp.Picture.upload.jup`,
        filePath: data.path[i],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",
          'Cookie': 'MEETREND_CRM_TOKEN=' + wx.getStorageSync('token')
        },
        formData: {
          'user': 'test'
        },
        success: function(res) {        
          var tempArr = that.data.saveQuaCertificate
          tempArr.push(JSON.parse(res.data).data.pictureId)
          that.setData({
            saveQuaCertificate: tempArr
          })
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
        },
        fail: function(e) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function() {
          i++
          data.i = i
          that.uploadQuaCertificate(data)
        }
      })
    }
  },

  uploadIdCertificate(data) {
    var that = this
    var i = data.i ? data.i : 0
    if (data.path.length === i) {
      that.uploadAwardCertificate({
        path: that.data.awardCertificate
      })
      return
    }
    var uuid = /[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/;
    if (uuid.test(data.path[i])) {
      var array = that.data.saveIdCertificate
      array.push(data.path[i])
      that.setData({
        saveIdCertificate: array
      })
      i++
      data.i = i
      that.uploadIdCertificate(data)
    } else {
      wx.uploadFile({
        url: `${config.api_base_url}api/Ecp.Picture.upload.jup`,
        filePath: data.path[i],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",
          'Cookie': 'MEETREND_CRM_TOKEN=' + wx.getStorageSync('token')
        },
        formData: {
          'user': 'test'
        },
        success: function(res) {
          var tempArr = that.data.saveIdCertificate
          tempArr.push(JSON.parse(res.data).data.pictureId)
          that.setData({
            saveIdCertificate: tempArr
          })
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
        },
        fail: function(e) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function() {
          i++
          data.i = i
          that.uploadIdCertificate(data)
        }
      })
    }
  },

  uploadAwardCertificate(data) {
    var that = this
    var i = data.i ? data.i : 0
    if (data.path.length === i) {
      that.saveData()
      return
    }
    var uuid = /[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/;
    if (uuid.test(data.path[i])) {
      var array = that.data.saveAwardCertificate
      array.push(data.path[i])
      that.setData({
        saveAwardCertificate: array
      })
      i++
      data.i = i
      that.uploadAwardCertificate(data)
    } else {
      wx.uploadFile({
        url: `${config.api_base_url}api/Ecp.Picture.upload.jup`,
        filePath: data.path[i],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",
          'Cookie': 'MEETREND_CRM_TOKEN=' + wx.getStorageSync('token')
        },
        formData: {
          'user': 'test'
        },
        success: function(res) {
          var tempArr = that.data.saveAwardCertificate
          tempArr.push(JSON.parse(res.data).data.pictureId)
          that.setData({
            saveAwardCertificate: tempArr
          })
          if (res.statusCode != 200) {
            wx.showModal({
              title: '提示',
              content: '上传失败',
              showCancel: false
            })
            return;
          }
        },
        fail: function(e) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
        },
        complete: function() {
          i++
          data.i = i
          that.uploadAwardCertificate(data)
        }
      })
    }
  },

  saveData() {
    var quaImg,idImg,awardImg
    for(var i = 0; i < this.data.saveQuaCertificate.length; i++) {
      if(i == 0) {
        quaImg = this.data.saveQuaCertificate[i]
      } else {
        quaImg = quaImg + '|' + this.data.saveQuaCertificate[i]
      }
    }

    for (var i = 0; i < this.data.saveIdCertificate.length; i++) {
      if (i == 0) {
        idImg = this.data.saveIdCertificate[i]
      } else {
        idImg = idImg + '|' + this.data.saveIdCertificate[i]
      }
    }

    for (var i = 0; i < this.data.saveAwardCertificate.length; i++) {
      if (i == 0) {
        awardImg = this.data.saveAwardCertificate[i]
      } else {
        awardImg = awardImg + '|' + this.data.saveAwardCertificate[i]
      }
    }
    if (this.data.authenticationInfo) {
      this.setData({
        'saveData.FId': this.data.authenticationInfo.FId ? this.data.authenticationInfo.FId:''
      })
    }
    this.setData({
      'saveData.FPrimarySeries': this.data.priSeries[this.data.priSeriesIndex].FId,
      'saveData.FPrimaryYear': this.data.priYears[this.data.priYearsIndex].value,
      'saveData.FSecondarySeries': this.data.secSeries[this.data.secSeriesIndex].FId,
      'saveData.FSecondaryYear': this.data.secYears[this.data.secYearsIndex].value,
      'saveData.FGatheringCode': this.data.saveGatheringCode,
      'saveData.FQualificationCertificate': quaImg,
      'saveData.FIdentityCardImg': idImg,
      'saveData.FAwardInformation': awardImg,
      'saveData.FRemark': this.data.otherDes,
      'saveData.FItEmpId': this.data.FItEmpId,
    })
    const saveDataToServer = authModel.saveData({
      args: {
        data: [this.data.saveData]
      }
    })
    saveDataToServer.then(res => {
      if(this.data.btnClickStatus === 'submit') {
        const submitDataToServer = authModel.submitData({
          args: {
            entityId: res.data.data.entityIds[0]
          }
        })
        submitDataToServer.then(res => {
          wx.hideLoading()
          wx.showModal({
            showCancel: false,
            title: '提示',
            content: '提交成功',
            success(res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          showCancel: false,
          title: '提示',
          content: '保存成功',
          success(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      }
    })
  },

  priSeriesSelector: function(e) {
    this.setData({
      priSeriesIndex: e.detail.value
    })
  },
  priYearsSelector: function(e) {
    this.setData({
      priYearsIndex: e.detail.value
    })
  },
  secSeriesSelector: function(e) {
    this.setData({
      secSeriesIndex: e.detail.value
    })
  },
  secYearsSelector: function(e) {
    this.setData({
      secYearsIndex: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '认证',
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#3B80FE',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    wx.showLoading({
      mask: true
    })
    if (options.FItEmpId) {
      this.setData({
        FItEmpId: options.FItEmpId
      })
    }
    const seriesData = authModel.getSeriesData({
      pageIndex: 1,
      refresh: 'true',
      unitId: '5570d564-d242-4495-a1ea-ad97459a8983',
      listId: '4e3a0ed8-c4ec-41db-92ac-f45670f6edff',
      pageCode: 'ATC.Series.List'
    })
    const dateDic = authModel.getYearsDic()
    const cerData = authModel.getSelfAuthData()
    Promise.all([seriesData, dateDic, cerData])
      .then(res => {
        let tempArr = []
        for (var i = 0; i < res[1].data.data.editJson.title.length; i++) {
          if (res[1].data.data.editJson.title[i].name = 'FPrimaryYear' && res[1].data.data.editJson.title[i].control == 'ComboBox') {
            tempArr = res[1].data.data.editJson.title[i].items
          }
        }
        this.setData({
          priSeries: res[0].data.data.data.records,
          secSeries: res[0].data.data.data.records,
          authenticationInfo: res[2].data.data.resumeData.authenticationInfoList[0] ? res[2].data.data.resumeData.authenticationInfoList[0]:[],
          priYears: tempArr,
          secYears: tempArr,
        })
        wx.hideLoading()
        this.initData()
      })
  },

  initData() {
    var priSeriesIndex, secSeriesIndex, priYearIndex, secYearIndex
    for (var i = 0; i < this.data.priSeries.length; i++) {
      if (this.data.priSeries[i].FId === this.data.authenticationInfo.FPrimarySeries) {
        priSeriesIndex = i
      }
      if (this.data.priSeries[i].FId === this.data.authenticationInfo.FSecondarySeries) {
        secSeriesIndex = i
      }
    }
    for (var i = 0; i < this.data.priYears.length; i++) {
      if (this.data.priYears[i].value === this.data.authenticationInfo.FPrimaryYear) {
        priYearIndex = i
      }
      if (this.data.priYears[i].value === this.data.authenticationInfo.FSecondaryYear) {
        secYearIndex = i
      }
    }
    this.setData({
      priSeriesIndex: priSeriesIndex ? priSeriesIndex:0,
      priYearsIndex: priYearIndex ? priYearIndex:0,
      secSeriesIndex: secSeriesIndex ? secSeriesIndex:0,
      secYearsIndex: secYearIndex ? secYearIndex:0,
      gatheringCode: this.data.authenticationInfo.FGatheringCode ? this.data.authenticationInfo.FGatheringCode:'',
      quaCertificate: this.data.authenticationInfo.FQualificationCertificate ? this.data.authenticationInfo.FQualificationCertificate.split('|') : [],
      idCertificate: this.data.authenticationInfo.FIdentityCardImg ? this.data.authenticationInfo.FIdentityCardImg.split('|') : [],
      awardCertificate: this.data.authenticationInfo.FAwardInformation ? this.data.authenticationInfo.FAwardInformation.split('|') : [],
      otherDes: this.data.authenticationInfo.FRemark ? this.data.authenticationInfo.FRemark:'',
    })
  },

  otherDesInput(e) {
    this.setData({
      otherDes: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})